package com.thti.mecool.client.service;

import com.thti.mecool.client.util.Util;

/**
 * 
 * @author weiguo.ren
 * 
 */

public class ReconnectionThread extends Thread {



    private final XmppManager xmppManager;

    private int waiting;

    ReconnectionThread(XmppManager xmppManager) {
        this.xmppManager = xmppManager;
        this.waiting = 0;
    }

    @Override
	public void run() {
        try {
            while (!isInterrupted()) {
                Util.print( "Trying to reconnect in " + waiting()
                        + " seconds");
                Thread.sleep(waiting() * 1000L);
                xmppManager.connect();
                
                waiting++;
            }
        } catch (final InterruptedException e) {
            xmppManager.getHandler().post(new Runnable() {
                @Override
				public void run() {
                    xmppManager.getConnectionListener().reconnectionFailed(e);
                }
            });
        }
    }

    private int waiting() {
        if (waiting > 20) {
            return 600;
        }
        if (waiting > 13) {
            return 300;
        }
        return waiting <= 7 ? 10 : 60;
    }
}
